#include <stdio.h>
#include <stdlib.h>//包含malloc函数
#include <string.h>//包含strcpy函数
/*第六章 指针相关代码*/
#define N 5
void change1(int* j){
    *j = 5;
}
int main1() {
    int i = 10;
    printf("before change i = %d\n",i);
    change1(&i);
    printf("after change i = %d\n",i);
    return 0;
}
//通过指针的间接访问改变变量i的值

int main2(){
    int a[N] = {1,2,3,4,5};
    int* p;
    int i;
    p = a;
    for(i = 0;i < N;i++){
        printf("%3d",*(p+i));
    }
    printf("\n-----------------\n");
    p= &a[4];
    for(i= 0;i < N;i++){
        printf("%3d",*(p-i));
    }
    printf("\n");
    return 0;
}

//通过指针修改数组元素
void change2(char* d){
    *d = 'H';
    d[1] = 'E';
    *(d+2) = 'L';
}
int main3(){
    char c[10] = "hello";
    change2(c);
    puts(c);
    return 0;
}

//6.5 指针与动态内存申请
int main4(){
    int i;
    char* p;
//    scanf("%d",&i);//为什么是“&i”而不是“i”
    scanf("%d",&i);
    p = (char*)malloc(i);
    strcpy(p,"malloc success");
    puts(p);
    free(p);
    printf("free success\n");
    return 0;
}

//6.5 栈空间与堆空间的差异
char* print_stack(){
    char c[17] = "I am print_stack";
    puts(c);//栈空间在执行这个函数后会被回收
    return c;
}

char* print_malloc(){
    char* p;
    p = (char*) malloc(20);
    strcpy(p,"I am print_malloc");
    puts(p);
    return p;
}
int main(){
    char* p;
    p = print_stack();
    printf("p = %s\n",p);
    p = print_malloc();
    puts(p);
    return 0;
}
/*这一段代码是为了表示：栈空间中的函数再执行一次后会被回收，而堆空间中的函数可以保存直到free函数启用*/